// MultiAttributeColor.js (c) 2012 matsuda
// Vertex shader program
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'attribute vec4 a_Color;\n' +
  'varying vec4 v_Color;\n' + // varying variable
  'void main() {\n' +
  '  gl_Position = a_Position;\n' +
  '  gl_PointSize = 10.0;\n' +
  '  v_Color = a_Color;\n' + // Pass the data to the fragment shader
  '}\n';

// Fragment shader program
var FSHADER_SOURCE =
  'precision mediump float;\n' + // Precision qualifier (See Chapter 6)
  'uniform float u_Width;\n' +
  'uniform float u_Height;\n' +
  'varying vec4 v_Color;\n' + // Receive the data from the vertex shader
  'void main() {\n' +
  // '  gl_FragColor = v_Color;\n' +
  '  gl_FragColor = vec4(gl_FragCoord.x/u_Width, 0.0, gl_FragCoord.y/u_Height, 1.0);\n' +
  '}\n';

var canvas = document.getElementById('example');
var gl = getWebGLContext(canvas);

function clear() {
  // Specify the color for clearing <canvas>
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // Clear <canvas>
  gl.clear(gl.COLOR_BUFFER_BIT);
}

function initVertexBuffers(gl) {
  var verticesColors = new Float32Array([
    // Vertex coordinates and color
    -1.0, 1.0, 1.0, 0.0, 0.0,
    -1.0, -1.0, 1.0, 0.0, 0.0,
    1.0, -1.0, 0.0, 0.0, 1.0,
    1.0, 1.0, 0.0, 1.0, 0.0,
  ]);
  var n = 3; // The number of vertices
  // Create a buffer object
  var vertexColorBuffer = gl.createBuffer();
  // Write the vertex coordinates and colors to the buffer object
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW);

  var FSIZE = verticesColors.BYTES_PER_ELEMENT;
  var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
  var u_Width = gl.getUniformLocation(gl.program, 'u_Width');
  var u_Height = gl.getUniformLocation(gl.program, 'u_Height');
  console.log(" gl.drawingBufferWidth", gl.drawingBufferWidth, gl.drawingBufferHeight)
  gl.uniform1f(u_Width, gl.drawingBufferWidth);
  gl.uniform1f(u_Height, gl.drawingBufferHeight);

  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 5, 0);
  gl.enableVertexAttribArray(a_Position); // Enable the assignment of the buffer object

  gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 5, FSIZE * 2);
  gl.enableVertexAttribArray(a_Color);
  return n;
}

function init() {
  let n = 0;
  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }

  if ((n = initVertexBuffers(gl)) < 0) {
    console.log('Failed to set the positions of the vertices');
    return;
  }

  clear();
  // Draw three points
  gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
}

function main() {
  console.log("main")
  console.log(gl)
  init();
}